package com.shwread.android.ui.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.LionWebViewActivity;
import com.shwread.android.qysw.activity.TrainExamCommonWebActivity;
import com.shwread.android.qysw.activity.TrainExamListMoreActivity;
import com.shwread.android.qysw.activity.TrainMyExamListMoreActivity;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.customview.MyGridView;
import com.shwread.android.ui.customview.TouchWebView;
import com.shwread.android.ui.page.NewTrainingExamPage;
import com.TrainActionHelp;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.OtherTextHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import logic.bean.TrainCoursewareBean;
import logic.bean.TrainCoursewareListBean;
import logic.bean.TrainExamBean;
import logic.bean.TrainExamListBean;
import logic.bean.TrainIndexModel;
import logic.bean.TrainLearnBean;
import logic.bean.TrainLearnListBean;
import logic.bean.TrainLearnList_ChapterBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.DateUtil;
import logic.util.PicassoUtil;
import logic.util.ScreenUtil;
import logic.util.Utils;


/***
 * 模块类型 1：接入蓝狮子 2：课件深入 3：题型考试主要演示用 4：学习记录 5: 排行榜
 *
 * @author Hss
 */
public class TrainExamContentView1
        extends
        LinearLayout
        implements
        OnClickListener {
    private static int PAGESIZE = 30;
    private Context mContext;
    private UserBean lastUser;
    private RelativeLayout contentRl;

    private ImageView switchImg;
    private View switchView;
    private AnimationDrawable switchDrawable;
    private RelativeLayout rl_blank_content;

    // 微视频->公共课堂
    private MyGridView view5;
    private TrainCoursewareAdapter microVideoAdapter;
    private List<TrainCoursewareListBean> microVideoListBeans = new ArrayList<TrainCoursewareListBean>();

    // 主题培训->企业课堂
    private MyGridView view2;                                                // 课件深入
    private TrainCoursewareAdapter coursewareAdapter;
    private List<TrainCoursewareListBean> listBeans;

    // 蓝狮子
    private TouchWebView view1;                                                // 蓝狮子
    private String accessToken;

    // 在线考试
    private MyGridView view3;                                                // 题型考试
    private View examView;
    private View myExamView;
    private MyGridView view3_1;
    private View examMore;
    private View myExamMore;
    private TrainExamListAdapter examListAdapter;
    private TrainMyExamListAdapter myExamListAdapter;
    private List<TrainExamListBean> examListBeans = new ArrayList<TrainExamListBean>();
    private List<TrainExamListBean> examMyListBeans = new ArrayList<TrainExamListBean>();

    // 学习记录
    private MyGridView view4;                                                // 学习记录
    private LearnListAdapter learnListAdapter;
    private List<TrainLearnListBean> learnListBeans = new ArrayList<TrainLearnListBean>();

    private List<TrainIndexModel> mModuleList;               //模块列表
    private int modelType = 1; // 1蓝狮子(->微视频)，2课件深入，3题型考试，4学习记录，5排行榜
    private int currentPage = 1;
    private int myRefreshFlag = 2; // 1为 下拉刷新， 2为得到数据
    private boolean hasMore = true;
    private TrainExamContentViewListener contentViewListener;
    private BaseBusinessActivity baseActivity;
    private boolean[] isShowChild;

    public TrainExamContentView1(Context context) {
        super(context);
        mContext = context;
        lastUser = UserDao.getInstance(context).getLastLoginUser();
        initView();
        setListener();
        // 默认获取第一个模块的数据
        init6View();
        get2Data(1);
    }

    private void initView() {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        View view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_view1, null);
        contentRl = (RelativeLayout) view.findViewById(R.id.new_trainexam_content_view);
        switchImg = (ImageView) view.findViewById(R.id.column_switch_img);
        switchView = view.findViewById(R.id.column_switch_layout);
        rl_blank_content = (RelativeLayout) view.findViewById(R.id.rl_blank_content);

        view1 = (TouchWebView) view.findViewById(R.id.new_trainexam_content_1_webview);
        view2 = (MyGridView) view.findViewById(R.id.new_trainexam_content_2_listview);
        view3 = (MyGridView) view.findViewById(R.id.new_trainexam_content_3_examlist);
        examMore = view.findViewById(R.id.new_trainexam_content_exam_more);
        view3_1 = (MyGridView) view.findViewById(R.id.new_trainexam_content_3_myexamlist);
        examView = view.findViewById(R.id.new_train_content_3_include_examlist_view);
        myExamView = view.findViewById(R.id.new_train_content_3_include_myexamlist_view);
        myExamMore = view.findViewById(R.id.new_trainexam_content_myexam_more);
        view4 = (MyGridView) view.findViewById(R.id.new_trainexam_content_4_expandablelistview);
        view5 = (MyGridView) view.findViewById(R.id.new_trainexam_content_5_listview);
        // 主题培训
        coursewareAdapter = new TrainCoursewareAdapter();
        view2.setAdapter(coursewareAdapter);
        // 在线考试->经典试题/我的考试
        examListAdapter = new TrainExamListAdapter();
        view3.setAdapter(examListAdapter);
        myExamListAdapter = new TrainMyExamListAdapter();
        view3_1.setAdapter(myExamListAdapter);
        // 学习记录
        learnListAdapter = new LearnListAdapter();
        view4.setAdapter(learnListAdapter);
        // 微视频
        microVideoAdapter = new TrainCoursewareAdapter();
        view5.setAdapter(microVideoAdapter);
        addView(view, lp);
    }

    private void setListener() {
        view5.setOnItemClickListener(new ExamItemClick(0));
        view2.setOnItemClickListener(new ExamItemClick(0));
        view3.setOnItemClickListener(new ExamItemClick(1));
        view3_1.setOnItemClickListener(new ExamItemClick(2));
        view4.setOnItemClickListener(new ExamItemClick(4));
        examMore.setOnClickListener(this);
        myExamMore.setOnClickListener(this);
    }

    public void setTrainExamContentViewListener(TrainExamContentViewListener contentViewListener) {
        this.contentViewListener = contentViewListener;
    }

    public void setActivity(BaseBusinessActivity activity) {
        baseActivity = activity;
    }

    public void setModuleList(List<TrainIndexModel> moduleList) {
        this.mModuleList = moduleList;
    }

    /*-----------------------------更新模块内容---------------------------------------------*/
    public void showModelData(int model, int refreshFlag) {
        updateSwitchView(0);
        //		contentRl.setFocusable(false);
        view1.setFocusable(false);
        view2.setFocusable(false);
        view3.setFocusable(false);
        view3_1.setFocusable(false);
        view4.setFocusable(false);
        view5.setFocusable(false);
        modelType = model;
        myRefreshFlag = refreshFlag;
        if (refreshFlag == 1) currentPage = 1;
        switch (model) {
            case 1:// 教育学习对接蓝狮子->微视频
                /*init1View();
				initLionData();*/
                if (refreshFlag == 2) {
                    microVideoListBeans.clear();
                    microVideoAdapter.notifyDataSetChanged();
                    updateSwitchView(0);// 显示动画
                }
                init6View();
                get2Data(1);
                break;
            case 2:// 课件深入
                if (refreshFlag == 2) {
                    listBeans.clear();
                    coursewareAdapter.notifyDataSetChanged();
                    updateSwitchView(0);// 显示动画
                }
                init2View();
                get2Data(2);

                break;
            case 3:// 题型考试
                if (refreshFlag == 2) {
                    examListBeans.clear();
                    examMyListBeans.clear();
                    examListAdapter.notifyDataSetChanged();
                    updateSwitchView(0);
                }
                init3View();
                get3Data();
                break;
            case 4:// 学习记录
                init4View();
                get4Data();
                break;
            case 5:// 排行榜
                init5View();
                contentViewListener.OnLoadDataCompleted(1);
                break;

        }
    }

    private void init6View() {
        view1.setVisibility(View.GONE);
        view2.setVisibility(View.GONE);
        view4.setVisibility(View.GONE);
        ((ViewGroup) view3.getParent()).setVisibility(View.GONE);
        ((ViewGroup) view3_1.getParent()).setVisibility(View.GONE);
        view5.setVisibility(View.VISIBLE);
    }

    private void init5View() {

    }

    private void init4View() {
        view1.setVisibility(View.GONE);
        view2.setVisibility(View.GONE);
        view4.setVisibility(View.VISIBLE);
        ((ViewGroup) view3.getParent()).setVisibility(View.GONE);
        ((ViewGroup) view3_1.getParent()).setVisibility(View.GONE);
        view5.setVisibility(View.GONE);
    }

    private void init3View() {
        view1.setVisibility(View.GONE);
        view2.setVisibility(View.GONE);
        view4.setVisibility(View.GONE);
        ((ViewGroup) view3.getParent()).setVisibility(View.VISIBLE);
        ((ViewGroup) view3_1.getParent()).setVisibility(View.VISIBLE);
        view5.setVisibility(View.GONE);
    }

    private void init2View() {
        view1.setVisibility(View.GONE);
        view2.setVisibility(View.VISIBLE);
        view4.setVisibility(View.GONE);
        ((ViewGroup) view3.getParent()).setVisibility(View.GONE);
        ((ViewGroup) view3_1.getParent()).setVisibility(View.GONE);
        view5.setVisibility(View.GONE);
    }

    private void init1View() {
        view5.setVisibility(View.GONE);
        view1.setVisibility(View.VISIBLE);
        view2.setVisibility(View.GONE);
        view4.setVisibility(View.GONE);
        ((ViewGroup) view3.getParent()).setVisibility(View.GONE);
        ((ViewGroup) view3_1.getParent()).setVisibility(View.GONE);
    }

    /***************************
     * 蓝狮子start
     ***************************/
    private void initLionData() {
        updateSwitchView(0);
        NewActionHelp.lionAppAuth(new OtherTextHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (TextUtils.isEmpty(responseString)) return;
                Logger.json(responseString);

                try {
                    final String token = new JSONObject(responseString).getString("token");
                    final String expireIn = new JSONObject(responseString).getString("expires_in");

                    // NewActionHelp.lionUserAuth(lastUser.getStaffId() + "00",
                    // token, tokenhandler);
                    NewActionHelp.lionUserAuth(lastUser.getStaffId() + "00", token, tokenhandler);
                    //					NewActionHelp.lionUserAuth("10000141", token, tokenhandler);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (TextUtils.isEmpty(responseString)) responseString = "";
            }
        });
    }

    private OtherTextHttpResponseHandler tokenhandler = new OtherTextHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            if (TextUtils.isEmpty(responseString)) return;
            Logger.json(responseString);
            try {
                accessToken = new JSONObject(responseString).getString("access_token");

                String url = NewActionHelp.BLUELION_URL + "/wechat";
                Map<String, String> webHeaders = new HashMap<String, String>();
                webHeaders.put("ACCESSTOKEN", accessToken);
                view1.getSettings().setJavaScriptEnabled(true);
                view1.setWebViewClient(new LionWebViewClient());
                view1.loadUrl(url, webHeaders);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (TextUtils.isEmpty(responseString)) responseString = "";
            Logger.e(responseString, throwable);
        }
    };

    class LionWebViewClient
            extends
            WebViewClient {
        //重写shouldOverrideUrlLoading方法，使点击链接后不使用其他的浏览器打开。
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            System.out.println("蓝狮子     " + url);
            Intent webIntent = new Intent(mContext, LionWebViewActivity.class);
            webIntent.putExtra("accessToken", accessToken);
            webIntent.putExtra("url", url);
            mContext.startActivity(webIntent);
            //如果不需要其他对点击链接事件的处理返回true，否则返回false
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            contentViewListener.OnLoadDataCompleted(1);
            updateSwitchView(1);
        }
    }

    /*************************** 蓝狮子end ***************************/
    /********************** 课件深入start 增加微视频******************************/
    /**
     * 获取课件深入的Action
     *
     * @param type 微视频 type=1,主题培训 type=2
     */
    private void get2Data(final int type) {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryTrainList(mContext, type, cid, currentPage, 10, new ObjectHttpResponseHandler<TrainCoursewareBean>() {

            @Override
            public Type getType() {
                return new TypeToken<TrainCoursewareBean>() {
                }.getType();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                // 通知 外部的调用者， 出错了。
                loadFail();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, final TrainCoursewareBean arg2, String arg3) {
                System.out.println("trainList---------" + arg2);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        // listBeans = arg2.trainList;
                        if (arg2.trainList == null || arg2.trainList.size() == 0) {
                            // 取到的内空为空
                            hasMore = false;
                            if (contentViewListener != null) {
                                contentViewListener.OnLoadDataCompleted(2);// 装载更多
                            }
                            if (currentPage == 1) {// 只有当前是重新刷新时，
                                // 才更新ui为无内容
                                updateSwitchView(2);// 内容为空
                            }
                            return;
                        }
                        // hasMore = listBeans.size() < PAGESIZE ? false
                        // : true;
                        hasMore = true;
                        if (currentPage == 1) {// 刷新
                            if (type == 2) {
                                listBeans = arg2.trainList;
                            } else if (type == 1) {
                                microVideoListBeans = arg2.trainList;
                            }

                        } else {// 取下一页
                            if (type == 2) {
                                listBeans.addAll(arg2.trainList);
                            } else if (type == 1) {
                                microVideoListBeans.addAll(arg2.trainList);
                            }
                        }
                        if (type == 2) {
                            coursewareAdapter.initData(listBeans);
                        } else if (type == 1) {
                            microVideoAdapter.initData(microVideoListBeans);
                        }
                        loadSuccess();

                    }
                });
            }
        });
    }

    /*private class TrainCoursewareAdapter
            extends
            BaseAdapter
    {

        private TrainCoursewareHolder         holder;
        private List<TrainCoursewareListBean> beans;

        public void initData(List<TrainCoursewareListBean> lists) {
            beans = lists;
            setListViewHeightBasedOnChildren(view2, 0);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return (beans == null || beans.isEmpty()) ? 0 : beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            TrainCoursewareListBean listBean = beans.get(position);
            if (view == null)
            {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_2_item, null);
                holder.view1 = view.findViewById(R.id.new_trainexam_content_2_rl1);
                holder.view1.setVisibility(View.VISIBLE);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_2_title);
                holder.tvIntro = (TextView) view.findViewById(R.id.new_trainexam_content_2_intro);
                holder.sivImage = (SmartImageView) view.findViewById(R.id.new_trainexam_content_2_image);
                holder.sivImage.setDefaultImg(100);
                holder.tvCount = (TextView) view.findViewById(R.id.new_trainexam_content_2_count);
                holder.tvAuthor = (TextView) view.findViewById(R.id.new_trainexam_content_2_author);
                holder.ivVedio = (ImageView) view.findViewById(R.id.new_trainexam_content_img);
                view.setTag(holder);
            }
            else
            {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null) return view;
            if (listBean.trainType == 3)
            {
                holder.ivVedio.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.ivVedio.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(listBean.name);
            holder.tvIntro.setText(listBean.shortIntro);
            holder.sivImage.setImageUrl(listBean.coverImg1);
            holder.tvCount.setText("集数:" + listBean.chapterNum);
            if (Utils.isEmpty(listBean.lecturerName)) holder.tvAuthor.setVisibility(View.GONE);
            else holder.tvAuthor.setText("讲师:" + listBean.lecturerName);
            return view;
        }
    }*/
    private class TrainCoursewareAdapter extends BaseAdapter {

        private TrainCoursewareHolder holder;
        private List<TrainCoursewareListBean> beans;

        public void initData(List<TrainCoursewareListBean> lists) {
            beans = lists;
			/* setListViewHeightBasedOnChildren(view2, 0); */
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return (beans == null || beans.isEmpty()) ? 0 : beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            TrainCoursewareListBean listBean = beans.get(position);
            if (view == null) {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_item_new, null);
                holder.view1 = view.findViewById(R.id.new_trainexam_content_item_ll1);
                holder.view1.setVisibility(View.VISIBLE);
                holder.view2 = view.findViewById(R.id.new_trainexam_content_item_ll2);
                holder.view2.setVisibility(View.GONE);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_item_title);
                holder.tvTitle.setLines(2);
                holder.sivImage = (ImageView) view.findViewById(R.id.new_trainexam_content_item_image);
                PicassoUtil.load(mContext, R.drawable.trainexam_default_img, holder.sivImage);
                holder.tvCount = (TextView) view.findViewById(R.id.new_trainexam_content_item_count);
                holder.tvTime = (TextView) view.findViewById(R.id.new_trainexam_content_item_time);
                holder.ivVedio = (ImageView) view.findViewById(R.id.new_trainexam_content_img);
                view.setTag(holder);
            } else {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null)
                return view;
            if (listBean.trainType == 3) {
                holder.ivVedio.setVisibility(View.GONE);
            } else {
                holder.ivVedio.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(listBean.name);
            //holder.tvIntro.setText(listBean.shortIntro); // 去掉简介字段
//			holder.sivImage.setImageUrl(listBean.coverImg1);
            PicassoUtil.load(mContext, listBean.coverImg1, R.drawable.trainexam_default_img, holder.sivImage);
			
			/*holder.tvCount.setText("集数:" + listBean.chapterNum);
			if (Utils.isEmpty(listBean.lecturerName))
				holder.tvTime.setVisibility(View.GONE);
			else
				holder.tvTime.setText("讲师:" + listBean.lecturerName);*/
            holder.tvTime.setVisibility(View.GONE);
            if (Utils.isEmpty(listBean.typeName)) {
                holder.tvCount.setText("类型:" + "");
            } else {
                holder.tvCount.setText("类型:" + listBean.typeName);
            }
            return view;
        }
    }

    private String getCourseWareUrl(int trainId, int trainType, String cid) {
        return TrainActionHelp.getUrl() + "toTrainChapterList.do?trainId=" + trainId + "&trainType=" + trainType + "&cid=" + cid;
    }

    private String getLearnRecordUrl(int trainId, String cid) {
        return TrainActionHelp.getUrl() + "toStudyAndExamLogs.do?trainId=" + trainId + "&cid=" + cid;
    }

    private String getExamListUrl(int id, String cid, int type) {
        String typeUrl = type == 1 ? "toExamInfoById.do" : "queryMyExamDetailsView.do";
        return TrainActionHelp.getUrl() + typeUrl + "?evaluationId=" + id + "&cid=" + cid;
    }

    private class TrainCoursewareHolder {
        TextView tvIntro, tvAuthor;
        ImageView sivImage; // ok
        ImageView ivVedio; // ok
        View view1, view2, view3; // view1,view2 ok


        TextView tvTitle, tvRight, tvWrong, tvScore, tvHandTime, tvUsedTime, tvRedo; // ok
        TextView tvCount, tvTime; // ok
    }
    /*********************** 课件深入end ***************************/

    /****************************
     * 学习记录start
     ************************************/
    void get4Data() {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryUserStudyRecord(mContext, 4, cid, currentPage, 10, new ObjectHttpResponseHandler<TrainLearnBean>() {

            @Override
            public Type getType() {
                return new TypeToken<TrainLearnBean>() {
                }.getType();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                loadFail();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, final TrainLearnBean arg2, String arg3) {
                Log.i(arg3);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        // listBeans = arg2.trainList;
                        if (arg2.trainList == null || arg2.trainList.size() == 0) {
                            // 取到的内空为空
                            hasMore = false;
                            if (contentViewListener != null) {
                                contentViewListener.OnLoadDataCompleted(2);// 装载更多
                            }
                            if (currentPage == 1) {// 只有当前是重新刷新时，
                                // 才更新ui为无内容
                                updateSwitchView(2);// 内容为空
                            }
                            return;
                        }
                        // hasMore = listBeans.size() < PAGESIZE ? false
                        // : true;
                        hasMore = true;
                        if (currentPage == 1) {// 刷新
                            learnListBeans = arg2.trainList;
                        } else {// 取下一页
                            learnListBeans.addAll(arg2.trainList);
                        }
                        isShowChild = new boolean[learnListBeans.size()];
                        learnListAdapter.notifyDataSetChanged();
						/*setListViewHeightBasedOnChildren(view4, 0);*/
                        loadSuccess();

                    }
                });
            }
        });
    }

    // expandableListview的适配器
	/*private class LearnListAdapter
	        extends
	        BaseAdapter
	{
		private LearnListHolder viewHolder;
		
		@Override
		public int getCount() {
			return learnListBeans.size();
		}
		
		@Override
		public Object getItem(int arg0) {
			return learnListBeans.get(arg0);
		}
		
		@Override
		public long getItemId(int arg0) {
			return 0;
		}
		
		@Override
		public View getView(final int groupPosition, View convertView, ViewGroup arg2) {
			final TrainLearnListBean listBean = learnListBeans.get(groupPosition);
			if (convertView == null)
			{
				viewHolder = new LearnListHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_myexam_content_item, null);
				viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_title);
				viewHolder.siv = (SmartImageView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_image);
				viewHolder.siv.setDefaultImg(100);
				viewHolder.tvReadTime = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_readtime);
				viewHolder.tvReadTo = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_readto);
				viewHolder.llHandTime = (LinearLayout) convertView.findViewById(R.id.ll_new_trainexam_myexam_content_item_handtime);
				viewHolder.tvHandTime = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_handtime);
				viewHolder.tvUseTime = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_usetime);
				viewHolder.tvUserScore = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_score);
				viewHolder.tvRedo = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_redo);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (LearnListHolder) convertView.getTag();
			}
			final List<TrainLearnList_ChapterBean> gbs = learnListBeans.get(groupPosition).chapterEvaluaList;
			//			if (hasChild(groupPosition))
			//			{
			//				viewHolder.vAbout.setVisibility(View.VISIBLE);
			//				viewHolder.tvAbout.setText(!isShowChild[groupPosition] ? "相关" + gbs.size() + "个评测" : "收起");
			//				if(!isShowChild[groupPosition])
			//				{
			//					viewHolder.ivAbout.setImageResource(R.drawable.new_treanlearn_item_open);
			//					viewHolder.lvChild.setVisibility(View.GONE);
			//					
			//				}else
			//				{
			//					viewHolder.ivAbout.setImageResource(R.drawable.new_treanlearn_item_close);
			//					viewHolder.lvChild.setVisibility(View.VISIBLE);
			//				}
			//			}
			//			else
			//			{
			//				viewHolder.vAbout.setVisibility(View.GONE);
			//			}
			//			if (listBean.hasExam.equals("n"))
			//			{
			//				viewHolder.tvCount.setVisibility(View.GONE);
			//				viewHolder.tvTotal.setVisibility(View.GONE);
			//				viewHolder.vPingRl.setVisibility(View.GONE);
			//			}
			//			else if (!listBean.joinedExam)
			//			{
			//				viewHolder.tvUndo.setVisibility(View.GONE);
			//				viewHolder.tvWrong.setVisibility(View.GONE);
			//				viewHolder.tvUserScore.setVisibility(View.GONE);
			//				viewHolder.tvRedo.setText("评测");
			//				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			//				viewHolder.tvRedo.setLayoutParams(lp);
			//			}
			//			else 
			if (Utils.isEmpty(listBean.examRepeatFlag) || listBean.examRepeatFlag.equals("n"))
			{
				viewHolder.tvRedo.setVisibility(View.GONE);
			}
			
			viewHolder.tvTitle.setText(listBean.name);
			viewHolder.tvReadTime.setText("阅读时间：" + DateUtil.getDateToMinuteForDot(listBean.studyTime));
			if (Utils.isNotEmpty(listBean.chapterName))
			{
				viewHolder.tvReadTo.setText("阅至：" + listBean.chapterName);
				viewHolder.tvReadTo.setVisibility(View.VISIBLE);
			}
			else
			{
				viewHolder.tvReadTo.setVisibility(View.GONE);
			}
			if (listBean.joinedExam)
			{
				viewHolder.llHandTime.setVisibility(View.VISIBLE);
				viewHolder.tvUseTime.setVisibility(View.VISIBLE);
				viewHolder.tvUserScore.setVisibility(View.VISIBLE);
				viewHolder.tvHandTime.setText("交卷时间：" + DateUtil.getDateToMinuteForDot(listBean.handPaperTime));
				if (listBean.userdTime < 60)
				{
					viewHolder.tvUseTime.setText("用时：" + listBean.userdTime + "秒");
				}
				else if (listBean.userdTime < 60 * 60)
				{
					int minutes = (int) (listBean.userdTime / 60);
					long seconds = listBean.userdTime - minutes * 60;
					viewHolder.tvUseTime.setText("用时：" + minutes + "分" + seconds + "秒");
				}
				else
				{
					viewHolder.tvUseTime.setText("用时：" + listBean.userdTime / 3600 + "小时");
				}
				if (listBean.userScore >= listBean.passScore)
				{
					viewHolder.tvUserScore.setText(Html.fromHtml("得分: " + listBean.userScore + "分" + " 通过"));
				}
				else
				{
					viewHolder.tvUserScore.setText(Html.fromHtml("得分: " + listBean.userScore + "分" + " 不通过"));
				}
			}
			else
			{
				viewHolder.tvRedo.setVisibility(View.GONE);
				viewHolder.llHandTime.setVisibility(View.GONE);
				viewHolder.tvUseTime.setVisibility(View.GONE);
				viewHolder.tvUserScore.setVisibility(View.GONE);
			}
			viewHolder.siv.setImageUrl(listBean.coverImg1);
			viewHolder.tvRedo.setOnClickListener(TrainExamContentView1.this);
			//			viewHolder.vAbout.setTag(groupPosition);
			//			viewHolder.vAbout.setOnClickListener(new AboutClick(viewHolder.lvChild, viewHolder.tvAbout, viewHolder.ivAbout));
			viewHolder.tvRedo.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View arg0) {
					NewTrainingExamPage.updateData = true;
					gotoRedo(listBean.evaluationId);
				}
			});
			viewHolder.siv.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					NewTrainingExamPage.updateData = true;
					String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
					Intent intent = new Intent(mContext, TrainExamCommonWebActivity.class);
					TrainLearnListBean bean = (TrainLearnListBean) getItem(groupPosition);
					intent.putExtra(DefaultConsts.title_s, "课件详情");
					intent.putExtra(DefaultConsts.req_url_s, getCourseWareUrl(bean.trainId, 0, cid));
					mContext.startActivity(intent);
				}
			});
			return convertView;
		}
		
		private boolean hasChild(int groupPosition) {
			List<TrainLearnList_ChapterBean> gbs = learnListBeans.get(groupPosition).chapterEvaluaList;
			if (gbs != null && gbs.size() > 0)
			{
				return true;
			}
			else return false;
		}
	}*/
    private class LearnListAdapter extends BaseAdapter {
        private LearnListHolder viewHolder;

        @Override
        public int getCount() {
            return learnListBeans.size();
        }

        @Override
        public Object getItem(int arg0) {
            return learnListBeans.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(final int groupPosition, View convertView,
                            ViewGroup arg2) {
            final TrainLearnListBean listBean = learnListBeans
                    .get(groupPosition);
            if (convertView == null) {
                viewHolder = new LearnListHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_myexam_content_item1, null);
                viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_title);
                viewHolder.siv = (ImageView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_image);
                PicassoUtil.load(mContext, R.drawable.trainexam_default_img, viewHolder.siv);
                // 阅读时间->学习时间
                viewHolder.tvReadTime = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_readtime);
                viewHolder.tvUserScore = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_score); // 成绩
                viewHolder.tvRedo = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_redo);
                viewHolder.progressBar = (ProgressBar) convertView.findViewById(R.id.new_trainexam_myexam_content_item_progress_bar);
                viewHolder.tvProgress = (TextView) convertView.findViewById(R.id.new_trainexam_myexam_content_item_progress_tv);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (LearnListHolder) convertView.getTag();
            }
            final List<TrainLearnList_ChapterBean> gbs = learnListBeans.get(groupPosition).chapterEvaluaList;
            if (Utils.isEmpty(listBean.examRepeatFlag)
                    || listBean.examRepeatFlag.equals("n")) { // 不可以重做
                viewHolder.tvRedo.setVisibility(View.INVISIBLE);
            }
            viewHolder.tvTitle.setText(listBean.name);
            if (listBean.joinedExam) {
                viewHolder.tvUserScore.setVisibility(View.VISIBLE);
                viewHolder.tvReadTime.setVisibility(View.GONE);
                if (listBean.userScore >= listBean.passScore) {
                    viewHolder.tvUserScore.setText(Html.fromHtml("成绩:" + listBean.userScore + "分" + " 通过"));
                } else {
                    viewHolder.tvUserScore.setText(Html.fromHtml("成绩:" + listBean.userScore + "分" + " 不通过"));
                }
            } else {
                viewHolder.tvRedo.setVisibility(View.INVISIBLE);
                viewHolder.tvUserScore.setVisibility(View.GONE);
                viewHolder.tvReadTime.setVisibility(View.VISIBLE);
                viewHolder.tvReadTime.setText("学习时间:" + DateUtil.getDateToMinuteForDot(listBean.studyTime));
            }
            viewHolder.progressBar.setProgress(listBean.percent);
            viewHolder.progressBar.setMax(100);
            if (listBean.percent > 100) {
                viewHolder.tvProgress.setText("100%");
            } else if (listBean.percent < 0) {
                viewHolder.tvProgress.setText("0%");
            } else {
                viewHolder.tvProgress.setText(listBean.percent + "%");
            }
//			viewHolder.siv.setImageUrl(listBean.coverImg1);
            PicassoUtil.load(mContext, listBean.coverImg1, R.drawable.trainexam_default_img, viewHolder.siv);
            viewHolder.tvRedo.setOnClickListener(TrainExamContentView1.this);
            viewHolder.tvRedo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    NewTrainingExamPage.updateData = true;
                    gotoRedo(listBean.evaluationId);
                }
            });
            viewHolder.siv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    NewTrainingExamPage.updateData = true;
                    String cid = QyreaderPerferencesUtil.getInstance(mContext,
                            Const.phone_number).getTrainIndexCid();
                    Intent intent = new Intent(mContext, TrainExamCommonWebActivity.class);
                    TrainLearnListBean bean = (TrainLearnListBean) getItem(groupPosition);
//					intent.putExtra(DefaultConsts.title_s, "课件详情");
                    intent.putExtra(DefaultConsts.title_s, getDetailTitle(modelType - 1));
                    intent.putExtra(DefaultConsts.req_url_s, getCourseWareUrl(bean.trainId, 0, cid));
                    mContext.startActivity(intent);
                }
            });
            return convertView;
        }

        private boolean hasChild(int groupPosition) {
            List<TrainLearnList_ChapterBean> gbs = learnListBeans
                    .get(groupPosition).chapterEvaluaList;
            if (gbs != null && gbs.size() > 0) {
                return true;
            } else
                return false;
        }
    }

    private class AboutClick
            implements
            OnClickListener {
        ListView lv;
        TextView tv;
        ImageView iv;

        public AboutClick(ListView l, TextView t, ImageView i) {
            lv = l;
            tv = t;
            iv = i;
        }

        @Override
        public void onClick(View arg0) {
            int position = (Integer) arg0.getTag();
            if (isShowChild[position]) {
                isShowChild[position] = false;
                lv.setVisibility(View.GONE);
                tv.setText("相关" + learnListBeans.get(position).chapterEvaluaList.size() + "个评测");
                iv.setImageResource(R.drawable.new_treanlearn_item_open);
                //setListViewHeightBasedOnChildren(view4, -learnListBeans.get(position).chapterEvaluaList.size());
            } else {
                isShowChild[position] = true;
                lv.setVisibility(View.VISIBLE);
                tv.setText("收起");
                iv.setImageResource(R.drawable.new_treanlearn_item_close);
                //setListViewHeightBasedOnChildren(view4, learnListBeans.get(position).chapterEvaluaList.size());
            }
        }

    }

    private class LearnListChildAdapter
            extends
            BaseAdapter {
        private List<TrainLearnList_ChapterBean> beans;
        private LearnListHolder viewHolder;

        public LearnListChildAdapter(List<TrainLearnList_ChapterBean> b) {
            beans = b;
        }

        @Override
        public int getCount() {
            return beans.size();
        }

        @Override
        public Object getItem(int arg0) {
            return beans.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(int arg0, View convertView, ViewGroup arg2) {
            final TrainLearnList_ChapterBean chapterBean = (TrainLearnList_ChapterBean) getItem(arg0);
            if (convertView == null) {
                viewHolder = new LearnListHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_4_child_item, null);
                viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.new_trainexam_content_4_child_title);
                viewHolder.siv = (ImageView) convertView.findViewById(R.id.new_trainexam_content_4_child_image);
                PicassoUtil.load(mContext, R.drawable.trainexam_default_img, viewHolder.siv);
                viewHolder.tvCount = (TextView) convertView.findViewById(R.id.new_trainexam_content_4_child_count);
                viewHolder.tvUserScore = (TextView) convertView.findViewById(R.id.new_trainexam_content_4_child_score);
                viewHolder.ivRedo = (ImageView) convertView.findViewById(R.id.new_trainexam_content_4_child_redo);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (LearnListHolder) convertView.getTag();
            }
            if (chapterBean.examRepeatFlag.equals("y")) {
                viewHolder.ivRedo.setVisibility(View.VISIBLE);
            } else viewHolder.ivRedo.setVisibility(View.GONE);
            viewHolder.tvTitle.setText(chapterBean.name);
            PicassoUtil.load(mContext, chapterBean.coverImg1, R.drawable.trainexam_default_img, viewHolder.siv);
            viewHolder.tvCount.setText("题数: " + chapterBean.examTotalNum);
            viewHolder.tvUserScore.setText(Html.fromHtml("得分: <font color=#EF5416>" + chapterBean.userScore + "</font>"));
            viewHolder.ivRedo.setOnClickListener(TrainExamContentView1.this);
            viewHolder.ivRedo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    gotoRedo(chapterBean.evaluationId);
                }
            });
            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    //view点击到子课件详情
                    gotoDetail(chapterBean);
                }
            });
            return convertView;
        }

    }

    class LearnListHolder {
        TextView tvTitle, tvIntro, tvCount, tvRedo, tvTotal, tvWrong, tvUndo, tvUserScore, tvAbout, tvReadTime, tvReadTo, tvHandTime, tvUseTime;
        ImageView siv;
        ImageView ivRedo, ivAbout;
        //View           vAbout, vPingRl;
        //ListView       lvChild;
        //LinearLayout   llHandTime;
        // 增加学习进度
        ProgressBar progressBar;
        TextView tvProgress;
    }

    private void gotoRedo(int id) {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        Intent intent = new Intent(mContext, TrainExamCommonWebActivity.class);
        intent.putExtra(DefaultConsts.title_s, getDetailTitle(modelType));
        //		intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + "toEvaluatingView.do? evaluationId=" + id + "&cid=" + cid);
        intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + "toEvaluatingView.do?cid=" + cid + "&evaluationId=" + id + "&isRepeat=y");
        //System.out.println(TrainActionHelp.getUrl() + "toEvaluatingView.do?cid=" + cid + "&evaluationId=" + id + "&isRepeat=y");
        mContext.startActivity(intent);
    }

    private void gotoDetail(TrainLearnList_ChapterBean chapterBean) {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        Intent intent = new Intent(mContext, TrainExamCommonWebActivity.class);
        intent.putExtra(DefaultConsts.title_s, "评测");
        intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + "queryChapterInfoView.do?trainId=" + chapterBean.trainId + "&chapterId=" + chapterBean.chapterId + "&cid=" + cid);
        //intent.putExtra(DefaultConsts.req_url_s,"http://192.168.0.146:8080/lqsw_website/" + "queryChapterInfoView.do?trainId=" + chapterBean.trainId + "&chapterId=" + chapterBean.chapterId + "&cid=" + cid);
        //System.out.println(TrainActionHelp.getUrl() + "queryChapterInfoView.do?trainId=" + chapterBean.trainId + "&chapterId=" + chapterBean.chapterId + "&cid=" + cid);
        mContext.startActivity(intent);
    }
    /**************************** 学习记录end ************************************/

    /***************************
     * 题型考试start 在线考试->经典试题和我的考试
     ***************************/
    private void get3Data() {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryExamList(mContext, 2, cid, currentPage, 4, new ObjectHttpResponseHandler<TrainExamBean>() {

            @Override
            public Type getType() {
                return new TypeToken<TrainExamBean>() {
                }.getType();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                // 通知 外部的调用者， 出错了。
                loadFail();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, final TrainExamBean arg2, String arg3) {
                System.out.println("trainList---------" + arg2);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {

                        // listBeans = arg2.trainList;
                        if (arg2.examList == null || arg2.examList.size() == 0) {
                            // 取到的内空为空
                            hasMore = false;
                            if (contentViewListener != null) {
                                contentViewListener.OnLoadDataCompleted(2);// 装载更多
                            }
                            if (currentPage == 1) {// 只有当前是重新刷新时，
                                // 才更新ui为无内容
                                updateSwitchView(2);// 内容为空
                            }
                            return;
                        }
                        // hasMore = listBeans.size() < PAGESIZE ? false
                        // : true;
                        hasMore = false;
                        //						if (currentPage == 1)
                        //						{// 刷新
                        examListBeans = arg2.examList;
                        //						}
                        //						else
                        //						{// 取下一页
                        //							examListBeans.addAll(arg2.examList);
                        //						}
                        if (examListBeans.size() > 3) {
                            examMore.setVisibility(View.VISIBLE);
                        } else examMore.setVisibility(View.GONE);
                        examListAdapter.initData(examListBeans);
                        loadSuccess();
                        qryMyExam();
                    }
                });
            }
        });
    }

    private void qryMyExam() {
        String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryMyExamList(mContext, cid, currentPage, 4, new ObjectHttpResponseHandler<TrainExamBean>() {

            @Override
            public Type getType() {
                return new TypeToken<TrainExamBean>() {
                }.getType();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                // 通知 外部的调用者， 出错了。
                //				loadFail();
                myExamView.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, final TrainExamBean arg2, String arg3) {
                System.out.println("mytrainList---------" + arg2.examList);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {

                        // listBeans = arg2.trainList;
                        if (arg2.examList == null || arg2.examList.size() == 0) {
                            // 取到的内空为空
                            hasMore = false;
                            if (contentViewListener != null) {
                                contentViewListener.OnLoadDataCompleted(2);// 装载更多
                            }
                            if (currentPage == 1) {// 只有当前是重新刷新时，
                                // 才更新ui为无内容
                                myExamView.setVisibility(View.GONE);
                            }
                            return;
                        }
                        // hasMore = listBeans.size() < PAGESIZE ? false
                        // : true;
                        hasMore = true;
                        //						if (currentPage == 1)
                        //						{// 刷新
                        examMyListBeans = arg2.examList;
                        if (examMyListBeans.size() > 3) {
                            myExamMore.setVisibility(View.VISIBLE);
                        } else myExamMore.setVisibility(View.GONE);
                        //						}
                        //						else
                        //						{// 取下一页
                        //							examMyListBeans.addAll(arg2.examList);
                        //						}
                        myExamListAdapter.initData(examMyListBeans);
                        loadSuccess();

                    }
                });
            }
        });
    }

    /*private class TrainExamListAdapter
            extends
            BaseAdapter
    {

        private TrainCoursewareHolder   holder;
        private List<TrainExamListBean> beans;

        public void initData(List<TrainExamListBean> lists) {
            beans = lists;
            setListViewHeightBasedOnChildren(view3, 0);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return (beans == null || beans.isEmpty()) ? 0 : beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            TrainExamListBean listBean = beans.get(position);
            if (view == null)
            {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_2_item, null);
                holder.view1 = view.findViewById(R.id.new_trainexam_content_2_rl1);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_2_title);
                holder.tvIntro = (TextView) view.findViewById(R.id.new_trainexam_content_2_intro);
                holder.sivImage = (SmartImageView) view.findViewById(R.id.new_trainexam_content_2_image);
                holder.sivImage.setDefaultImg(100);
                holder.tvCount = (TextView) view.findViewById(R.id.new_trainexam_content_2_count);
                holder.tvAuthor = (TextView) view.findViewById(R.id.new_trainexam_content_2_author);
                view.setTag(holder);
            }
            else
            {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null) return view;
            holder.tvTitle.setText(listBean.title);
            holder.view1.setVisibility(View.VISIBLE);
            holder.tvIntro.setText(listBean.shortIntro);
            holder.sivImage.setImageUrl(listBean.coverImg);
            holder.tvCount.setText("题数:" + listBean.examItemNum);
            holder.tvAuthor.setText("时间:" + listBean.limitTime / 60 + "分钟");
            return view;
        }
    }*/
    private class TrainExamListAdapter extends BaseAdapter { // 在线考试->经典试题

        private TrainCoursewareHolder holder;
        private List<TrainExamListBean> beans;

        public void initData(List<TrainExamListBean> lists) {
            beans = lists;
			/* setListViewHeightBasedOnChildren(view3, 0); */
            //setListViewHeightBasedOnChildren1(view3);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return (beans == null || beans.isEmpty()) ? 0 : beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            TrainExamListBean listBean = beans.get(position);
            if (view == null) {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_item_new, null);

                holder.view1 = view.findViewById(R.id.new_trainexam_content_item_ll1);
                holder.view2 = view.findViewById(R.id.new_trainexam_content_item_ll2);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_item_title);
                holder.tvTitle.setLines(2);
                holder.sivImage = (ImageView) view.findViewById(R.id.new_trainexam_content_item_image);
                PicassoUtil.load(mContext, R.drawable.trainexam_default_img, holder.sivImage);
                holder.tvCount = (TextView) view.findViewById(R.id.new_trainexam_content_item_count);
                holder.tvTime = (TextView) view.findViewById(R.id.new_trainexam_content_item_time);
                //holder.tvRedo = (TextView) view.findViewById(R.id.new_trainexam_content_item_redo);
                view.setTag(holder);
            } else {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null)
                return view;
            holder.view1.setVisibility(View.VISIBLE);
            holder.view2.setVisibility(View.GONE);
            //holder.tvRedo.setVisibility(View.GONE);
            holder.tvTitle.setText(listBean.title);
            PicassoUtil.load(mContext, listBean.coverImg, R.drawable.trainexam_default_img, holder.sivImage);
            holder.tvCount.setText("题数:" + listBean.examItemNum);
            holder.tvTime.setText("时间:" + listBean.limitTime / 60 + "分钟");
            return view;
        }
    }
    // 在线考试->我的考试
	/*private class TrainMyExamListAdapter
	        extends
	        BaseAdapter
	{
		
		private TrainCoursewareHolder   holder;
		private List<TrainExamListBean> beans;
		
		public void initData(List<TrainExamListBean> lists) {
			beans = lists;
			setListViewHeightBasedOnChildren(view3_1, 0);
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return (beans == null || beans.isEmpty()) ? 0 : beans.size();
		}
		
		@Override
		public Object getItem(int position) {
			return beans.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final TrainExamListBean listBean = beans.get(position);
			if (view == null)
			{
				holder = new TrainCoursewareHolder();
				view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_2_item, null);
				holder.view2 = view.findViewById(R.id.new_trainexam_content_2_rl2);
				holder.sivImage = (SmartImageView) view.findViewById(R.id.new_trainexam_content_2_image);
				holder.sivImage.setDefaultImg(100);
				holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_2_title);
				holder.tvRight = (TextView) view.findViewById(R.id.new_trainexam_content_2_right);
				holder.tvWrong = (TextView) view.findViewById(R.id.new_trainexam_content_2_wrong);
				holder.tvScore = (TextView) view.findViewById(R.id.new_trainexam_content_2_scores);
				holder.tvHandTime = (TextView) view.findViewById(R.id.new_trainexam_content_2_handtime);
				holder.tvUsedTime = (TextView) view.findViewById(R.id.new_trainexam_content_2_usetime);
				holder.tvRedo = (TextView) view.findViewById(R.id.new_trainexam_content_2_redo);
				holder.view3 = view.findViewById(R.id.new_trainexam_content_pingRl);
				view.setTag(holder);
			}
			else
			{
				holder = (TrainCoursewareHolder) view.getTag();
			}
			if (listBean == null) return view;
			holder.tvTitle.setText(listBean.title);
			holder.view2.setVisibility(View.VISIBLE);
			holder.view3.setVisibility(View.VISIBLE);
			holder.sivImage.setImageUrl(listBean.coverImg);
			holder.tvScore.setText(Html.fromHtml("得分：<font color=#EF5416> " + listBean.userScore + "</font>"));
			holder.tvHandTime.setText("交卷时间:" + formatHandTime(listBean.handPaperTime));
			holder.tvUsedTime.setText("用时:" + formatUsedTime(listBean.usedTime));
			holder.tvRight.setText(Html.fromHtml("做对: <font color=#EF5416>" + listBean.rightNum + "</font>"));
			holder.tvWrong.setText(Html.fromHtml("做错: <font color=#EF5416>" + (listBean.examItemNum - listBean.rightNum) + "</font>"));
			if (listBean.examRepeatFlag.equals("n"))
			{
				holder.tvRedo.setVisibility(View.GONE);
			}
			holder.tvRedo.setOnClickListener(TrainExamContentView1.this);
			holder.tvRedo.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0) {
					gotoRedo(listBean.evaluationId);
				}
			});
			return view;
		}
	}*/

    private class TrainMyExamListAdapter extends BaseAdapter {

        private TrainCoursewareHolder holder;
        private List<TrainExamListBean> beans;

        public void initData(List<TrainExamListBean> lists) {
            beans = lists;
			/*setListViewHeightBasedOnChildren(view3_1, 0); */
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return (beans == null || beans.isEmpty()) ? 0 : beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            final TrainExamListBean listBean = beans.get(position);
            if (view == null) {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.new_trainexam_content_item_new, null);
                holder.view1 = view.findViewById(R.id.new_trainexam_content_item_ll1);
                holder.view2 = view.findViewById(R.id.new_trainexam_content_item_ll2);
                holder.sivImage = (ImageView) view.findViewById(R.id.new_trainexam_content_item_image);
                PicassoUtil.load(mContext, R.drawable.trainexam_default_img, holder.sivImage);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_item_title);
                holder.tvTitle.setMaxLines(1);
                holder.tvRight = (TextView) view.findViewById(R.id.new_trainexam_content_item_right);
                holder.tvWrong = (TextView) view.findViewById(R.id.new_trainexam_content_item_wrong);
                holder.tvScore = (TextView) view.findViewById(R.id.new_trainexam_content_item_scores);
                holder.tvHandTime = (TextView) view.findViewById(R.id.new_trainexam_content_item_handtime);
                holder.tvRedo = (TextView) view.findViewById(R.id.new_trainexam_content_item_redo);
                view.setTag(holder);
            } else {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null)
                return view;
            holder.tvTitle.setText(listBean.title);
            holder.view1.setVisibility(View.GONE);
            holder.view2.setVisibility(View.VISIBLE);
            holder.tvRedo.setVisibility(View.VISIBLE);
            PicassoUtil.load(mContext, listBean.coverImg, R.drawable.trainexam_default_img, holder.sivImage);
            holder.tvScore.setText(Html.fromHtml("得分:<font color=#EF5416> " + listBean.userScore + "</font>"));
            holder.tvHandTime.setText("交卷时间:" + formatHandTime(listBean.handPaperTime));
			/*holder.tvUsedTime.setText("用时:" + formatUsedTime(listBean.usedTime));*/
            holder.tvRight.setText(Html.fromHtml("做对:<font color=#EF5416>" + listBean.rightNum + "</font>"));
            holder.tvWrong.setText(Html.fromHtml("做错:<font color=#EF5416>" + (listBean.examItemNum - listBean.rightNum) + "</font>"));
            if (listBean.examRepeatFlag.equals("n")) {
                holder.tvRedo.setVisibility(View.GONE);
            }
            holder.tvRedo.setOnClickListener(TrainExamContentView1.this);
            holder.tvRedo.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    gotoRedo(listBean.evaluationId);
                }
            });
            return view;
        }
    }

    private String formatUsedTime(int time) {
        int minute = 0;
        int hour = 0;
        hour = time / 60;
        minute = time % 60;
        if (hour < 1) {
            return minute + "秒";
        }
        return hour + "分" + minute + "秒";
    }

    private String formatHandTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(new Date(time));
    }

    /***************************************
     * 题型考试end
     *********************************/
    public static interface TrainExamContentViewListener {
        /**
         * @param flag 1为首次装载， 2 为装载更多
         */
        public void OnLoadDataCompleted(int flag);
    }

    /**
     * 栏目切换加载动画
     *
     * @param flag 0:加载中，1：加载完成，2: 内容为空 -1：加载失败
     */
    private void updateSwitchView(int flag) {
        switch (flag) {
            case -1:
                switchView.setVisibility(View.VISIBLE);
                rl_blank_content.setVisibility(View.GONE);
                contentRl.setVisibility(View.GONE);
                if (switchDrawable != null && switchDrawable.isRunning()) {
                    switchDrawable.stop();
                }
                // TODO
                switchImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                switchView.setVisibility(View.VISIBLE);
                contentRl.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                switchImg.setBackgroundResource(R.drawable.home_progress);
                // switchImg.setBackgroundResource(R.anim.column_switch_anim);
                switchDrawable = (AnimationDrawable) switchImg.getBackground();
                switchDrawable.start();
                break;
            case 1:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                contentRl.setVisibility(View.VISIBLE);
                break;
            case 2:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.VISIBLE);
                contentRl.setVisibility(View.GONE);
                break;
        }
    }

    public int getDataSize() {
        int count = 0;
        switch (modelType) {
            case 1:
                count = (microVideoListBeans == null || microVideoListBeans.isEmpty()) ? 0 : microVideoListBeans.size();
                break;
            case 2:
                count = (listBeans == null || listBeans.isEmpty()) ? 0 : listBeans.size();
                break;
            case 3:
                count = (examListBeans == null || examListBeans.isEmpty()) ? 0 : examListBeans.size();
                break;
            case 4:
                count = (learnListBeans == null || learnListBeans.isEmpty()) ? 0 : learnListBeans.size();
                break;
        }
        return count;
    }

    public boolean getHasMore() {
        return hasMore;
    }

    public void getNextPage() {
        currentPage++;
        switch (modelType) {
            case 1:
                get2Data(1);
                break;
            case 2:
                get2Data(2);
                break;
            case 3:
                currentPage = 1;
                get3Data();
                break;
            case 4:
                get4Data();
                break;
        }
    }

    private class ExamItemClick
            implements
            OnItemClickListener {
        private int type;

        public ExamItemClick(int t) {
            type = t;
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String cid = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number).getTrainIndexCid();
            Intent intent = new Intent(mContext, TrainExamCommonWebActivity.class);
            // 传模块标题
            intent.putExtra(DefaultConsts.title_s, getDetailTitle(modelType));
            if (type == 1 || type == 2) {
                //题型考试到详情
                TrainExamListBean bean = ((TrainExamListBean) arg0.getAdapter().getItem(arg2));
                if (type == 1) {
                    intent.putExtra(DefaultConsts.title_s, "考试");
                } else {
                    intent.putExtra(DefaultConsts.title_s, "我的考试");
                }
                intent.putExtra(DefaultConsts.req_url_s, getExamListUrl(bean.evaluationId, cid, type));
                NewTrainingExamPage.updateData = true;
            } else if (type == 0) {
                //课件深入到课件详情
                TrainCoursewareListBean bean = ((TrainCoursewareListBean) arg0.getAdapter().getItem(arg2));
                //intent.putExtra(DefaultConsts.title_s, "课件详情");
                intent.putExtra(DefaultConsts.req_url_s, getCourseWareUrl(bean.trainId, bean.trainType, cid));
            } else if (type == 4) {
                //学习记录主item点击到课件详情
                TrainLearnListBean bean = ((TrainLearnListBean) arg0.getAdapter().getItem(arg2));
                //intent.putExtra(DefaultConsts.title_s, "课件详情");
                intent.putExtra(DefaultConsts.req_url_s, getLearnRecordUrl(bean.trainId, cid));
            } else if (type == 5) {
                //学习记录子item点击到子课件详情
            }
            mContext.startActivity(intent);
        }
    }

    /**
     * 获取详情页的模块名字
     *
     * @param type
     * @return
     */
    private String getDetailTitle(int type) {
        String name = "";
        if (mModuleList != null && mModuleList.size() > 0) {
            TrainIndexModel model = mModuleList.get(type - 1);
            name = model.getName();
        }
        return name;
    }

    private void loadSuccess() {
        if (currentPage == 1) {// 刷新
            updateSwitchView(1);// 隐藏动画
            if (contentViewListener != null) {
                contentViewListener.OnLoadDataCompleted(1);
            }
        } else {// 取下一页
            if (contentViewListener != null) {
                contentViewListener.OnLoadDataCompleted(2);// 装载更多
            }
        }
    }

    private void loadFail() {
        baseActivity.getUIHandler().post(new Runnable() {
            @Override
            public void run() {
                if (contentViewListener != null) {
                    contentViewListener.OnLoadDataCompleted(2);// 装载更多
                }
                updateSwitchView(-1);// 加载失败
            }
        });
    }

    int childSize;

    public void setListViewHeightBasedOnChildren(ListView listView, int size) {

        childSize += size == 0 ? 0 : size;
        // 获取ListView对应的Adapter
        BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        totalHeight += (childSize > 0 ? childSize : 0) * ScreenUtil.dip2px(54);
        params.height = totalHeight + ScreenUtil.dip2px(10) * listAdapter.getCount();
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //更多点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.new_trainexam_content_exam_more:
                mContext.startActivity(new Intent(mContext, TrainExamListMoreActivity.class));
                break;
            case R.id.new_trainexam_content_myexam_more:
                mContext.startActivity(new Intent(mContext, TrainMyExamListMoreActivity.class));
                break;
        }
    }
}
